/*
 * Texture.cpp
 *
 *  Created on: 2012/07/06
 *      Author: weihe
 */

#include "Texture.h"
#include <iostream>
#include "stb_image.h"
#include <gl/glut.h>
#include "utility.h"

using namespace std;

namespace object {

Texture::Texture(string file, bool useAlpha)
{
	glEnable(GL_TEXTURE_2D);
	int width, height, comp;
	unsigned char *image = stbi_load(file.c_str(), &width, &height, &comp,
			useAlpha ? STBI_rgb_alpha : STBI_rgb);
	cout << width << " " << height << " " << comp << endl;
	if (!image) {
		cerr << "can't open file: " << file << endl;
		return;
	}
	cout << hex << (int) *((int*) image) << endl;
	cout << hex << (int) *((int*) image + 4) << endl;
	cout << hex << (int) *((int*) image + 8) << endl;
	texture = getUid();
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	int glcomp = useAlpha ? GL_RGBA : GL_RGB;
	glTexImage2D(GL_TEXTURE_2D, 0, glcomp, width, height, 0, glcomp,
			GL_UNSIGNED_BYTE, image);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	stbi_image_free(image);
}

Texture::~Texture()
{
	glDeleteTextures(1, &texture);
}

void Texture::bind() const
{
	glBindTexture(GL_TEXTURE_2D, texture);
}

} /* namespace object */
